﻿using DocumentMakingTools.Models;
using DocumentMakingTools.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DocumentMakingTools.ViewModels
{
    class ContractViewModel : ViewModelBase
    {
        Page page;
        private string name;
        public string Name
        { get => name; set { SetProperty(ref name, value); } }
        private string id;
        public string ID
        { get => id; set { SetProperty(ref id, value); } }
        public Command ViewTamplateCommand { get; set; }
        public Command AddItemCommand { get; set; }
        public Command BuildDocCommand { get; set; }
        public Command ClearItemsCommand { get; set; }
        public Command ItemTappedCommand { get; set; }
        public ObservableCollection<ContractItemModel> Items { get; set; }
        public ContractViewModel(Page page)
        {
            this.page = page;

            Items = new ObservableCollection<ContractItemModel>();

            ViewTamplateCommand = new Command(ExecuteViewTamplateCommand);
            AddItemCommand = new Command(ExecuteAddItemCommand);
            ItemTappedCommand = new Command((object obj) => ExecuteItemTappedCommand(obj));
            ClearItemsCommand = new Command(ExecuteClearItemsCommand);
            BuildDocCommand = new Command(ExecuteBuildDocCommand);
        }
        void ExecuteViewTamplateCommand()
        {
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("https://www.pincai.com/article/2390242.htm") { UseShellExecute = true });
        }
        async void ExecuteAddItemCommand()
        {
            if (!string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(ID))
                Items.Add(new ContractItemModel
                {
                    ID = ID,
                    Name = Name
                });
            else
                await page.DisplayAlert("警告", "著作权人姓名或身份证号为空", "确定");
        }
        async void ExecuteBuildDocCommand()
        {
            var softname = await page.DisplayPromptAsync("提示", "请输入软件名称");
            var path = Path.Combine(App.AppSetting.DefaultOutputPath, $"合同-{softname}.docx");
            using var service = new WordDocumentService(path);
            service.BuildAndSaveContract(Items.ToList(), softname);
            if (App.AppSetting.DefaultOpenCodeDocumentMode)
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(path) { UseShellExecute = true });
        }
        void ExecuteClearItemsCommand()
        {
            Items.Clear();
        }
        async void ExecuteItemTappedCommand(object obj)
        {
            var item = obj as ContractItemModel;
            if (await page.DisplayAlert("提示", $"确定删除{item.Name}吗？", "确定", "取消"))
                Items.Remove(item);
        }
    }
}
